#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <strings.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>

#define PORT 8888

int main()
{
	struct sockaddr_in server;
	int ret;
	bzero(&server,sizeof(server));
	server.sin_family = AF_INET;
	inet_pton(AF_INET,"127.0.0.1",&server.sin_addr);
	server.sin_port = htons(PORT);
	
	int listenfd = socket(AF_INET, SOCK_STREAM , 0 );
	assert(listenfd>=0);
	ret = bind(listenfd, (struct sockaddr*)&server , sizeof(server));
	assert(ret != -1);
	ret = listen(listenfd , 5);
	assert(ret !=-1);
	struct sockaddr_in  client;
	int client_len = sizeof(client);
	int connfd = accept(listenfd , (struct sockaddr *)&client , &client_len);
	if(connfd <0)
	{
		printf("errno is %d\n",errno);
		close(listenfd);
	}
	char buffer[1024];
	fd_set read_fds;
	fd_set exception_fds;
	FD_ZERO(&read_fds);
	FD_ZERO(&exception_fds);
	
	while(1)
	{
		memset(buffer,'\0',sizeof(buffer));
		FD_SET(connfd, &read_fds);
		FD_SET(connfd,&exception_fds);
		ret = select(connfd+1 , &read_fds, NULL,&exception_fds,NULL);
		if(ret<0)
		{
			printf("selection failure \n ");
			break;
		}	
		
		if(FD_ISSET(connfd, &read_fds))
		{
			 ret = recv(connfd, buffer, sizeof(buffer)-1 , 0);
			 if(ret <=0)
				break;
			 printf("get %d bytes of normal data : %s \n", ret ,buffer);
		}else if(FD_ISSET(connfd, &exception_fds))
		{
			 ret = recv(connfd, buffer, sizeof(buffer)-1 , MSG_OOB);
			 if(ret <=0)
				break;
			 printf("get %d bytes of normal data : %s \n", ret ,buffer);
 
		}

	}	

	close(connfd);
	close(listenfd);
	return 0;
}	
